let server = require("express")();
let mysql = require("mysql");
let expressStatic = require("express-static");
let ejs = require("ejs");
let port = 8080;

// 规划链接
let sql = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'yougou'
});

// 尝试链接
sql.connect();


//解决跨域
// server.all("*", function(req, res, next) {
//     //设置允许跨域的域名，*代表允许任意域名跨域
//     res.header("Access-Control-Allow-Origin", "*");
//     //允许的header类型
//     res.header("Access-Control-Allow-Headers", "content-type");
//     //跨域允许的请求方式 
//     res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
//     if (req.method.toLowerCase() == 'options')
//         res.send(200); //让options尝试请求快速结束
//     else
//         next();
// })


//注册按钮
server.get("/goregister", function(request, response) {
    let username = request.query.username;
    let password = request.query.password;
    sql.query(`SELECT * FROM user WHERE username="${username}"`, function(error, data) {
        if (error) {
            console.log(error);
            response.end("error");
            return;
        }
        if (data.length === 0) {
            sql.query(`INSERT INTO user (username,password) VALUES ("${username}","${password}")`, function(error, data) {
                if (error) {
                    console.log(error);
                    response.end("error");
                    return;
                }
                console.log("新用户注册成功！");
                response.end("success");
            })
        } else {
            console.log("该用户已被注册！");
            response.end("exist");
        }
    })

})


//去登陆按钮
server.get(`/goLogin`, function(request, response) {

    let username = request.query.username;
    let password = request.query.password;

    sql.query(`SELECT * FROM user WHERE username="${username}"`, function(error, data) {
        if (error) {
            console.log(error);
            response.end("error");
            return;

        }

        if (data.length === 0) {
            console.log("该用户不存在！");
            response.end("none");
            return;
        }
        if (data[0].password === password) {
            console.log("登录成功");
            response.end("success")
        } else {
            console.log("用户名或密码输入错误");
            response.end("error")
        }

    })
})

//跳转列表页
server.get(`/goodslist`, function(request, response) {
    sql.query(`SELECT * FROM goods`, function(error, data) {
        if (error) {
            console.log(error);
            response.end("error");
            return;
        }

        ejs.renderFile(`static/goodslist.html`, { goodslist: data }, function(error, result) {
            if (error) {
                console.log(error);
                return;
            }
            console.log("列表页加载成功");
            response.end(result);
        })
    })
})

//跳转详情页
server.get(`/gooddetail`, function(request, response) {
    let id = request.query.id;
    sql.query(`SELECT * FROM goods WHERE id="${id}"`, function(error, data) {
        if (error) {
            console.log(error);
            response.end("error");
            return;
        }

        ejs.renderFile(`static/gooddetail.html`, { details: data }, function(error, result) {
            if (error) {
                console.log(error);
                return;
            }
            console.log("详情页加载成功");
            response.end(result);
        })
    })
})


//加载购物车页面
server.get(`/car`, function(request, response) {
    let username = request.query.username;
    sql.query(`SELECT * FROM car WHERE username="${username}"`, function(error, data) {
        if (error) {
            console.log(error);
            response.end("error")
            return;
        }
        // if (data.length === 0) {
        //     // response.end("none");
        //     ejs.renderFile(`static/car.html`, { none: data }, function(error, result) {
        //         if (error) {
        //             console.log(error);
        //             return;
        //         }
        //         console.log("购物车页加载成功");
        //         response.end(result);
        //     })
        //     console.log("该用户没有加入商品");

        // } else {
        ejs.renderFile(`static/car.html`, { cars: data }, function(error, result) {
                if (error) {
                    console.log(error);
                    return;
                }
                console.log("购物车页加载成功");
                response.end(result);
            })
            //     }
    })
})


//点击加入购物车，向数据库里添加商品数据
server.get(`/insert`, function(request, response) {
    let username = request.query.username;
    let img = request.query.img;
    let gname = request.query.gname;
    let price = request.query.price;
    let count = request.query.count;

    sql.query(`SELECT * FROM car WHERE username="${username}" AND gname="${gname}"`, function(error, data) {
        if (error) {
            console.log(error);
            response.end("error")
            return;
        }
        if (data.length === 0) {
            sql.query(`INSERT INTO car (username,img,gname,price,count) VALUES ("${username}","${img}","${gname}","${price}","${count}")`, function(error, data) {
                if (error) {
                    console.log(error);
                    response.end("error")
                    return;
                }
                response.end("success");
                console.log("该商品成功加入购物车");
            })
        } else {
            sql.query(`UPDATE car SET count=count+${count} WHERE gname="${gname}"`, function(error, data) {
                {
                    if (error) {
                        console.log(error);
                        response.end("error")
                        return;
                    }
                    console.log("重复数据更新成功");
                    response.end("success");
                }
            })
        }
    })

})

//点击加减号更新数据库内容
server.get(`/change`, function(request, response) {
    let count = request.query.count;
    let gname = request.query.gname;

    sql.query(`UPDATE car SET count=${count} WHERE gname="${gname}"`, function(error, data) {
        {
            // console.log(count)
            if (error) {
                console.log(error);
                response.end("error")
                return;
            }
            // console.log(data)
            console.log("数据更新成功");
            response.end("success");
        }
    })
})


//清空购物车按钮
server.get(`/delete`, function(request, response) {
    let username = request.query.username;
    sql.query(`DELETE FROM car WHERE username="${username}"`, function(error, data) {
        if (error) {
            console.log(error);
            response.end("error")
            return;
        }
        console.log("该用户购物车删除成功");
        response.end('success');
    })
})

//点击删除按钮
server.get(`/remove`, function(request, response) {
    let gname = request.query.gname;
    sql.query(`DELETE FROM car WHERE gname="${gname}"`, function(error, data) {
        if (error) {
            console.log(error);
            response.end("error");
            return;
        }
        console.log("该条购物车信息删除成功");
        response.end("success")

    })
})

//加载订单页面
server.get(`/toapply`, function(request, response) {
    let username = request.query.username;
    let img = request.query.img;
    let gname = request.query.gname;
    let gprice = request.query.gprice;
    let count = request.query.count;
    let sum = request.query.sum;
    let ispay = request.query.ispay;

    //收到数据先查找是否有相同的商品
    sql.query(`SELECT * FROM apply WHERE username="${username}" AND gname="${gname}"`, function(error, data) {
        if (error) {
            console.log(error);
            response.end("error");
            return;
        }
        // console.log(data);

        if (data.length === 0) {
            sql.query(`INSERT INTO apply (username,img,gname,gprice,count,sum,ispay) VALUES ("${username}","${img}","${gname}","${gprice}","${count}","${sum}","${ispay}")`, function(error, data) {
                if (error) {
                    console.log(error);
                    response.end("error")
                    return;
                }
                console.log("去支付新商品插入成功");
                sql.query(`SELECT * FROM apply WHERE username=${username} AND ispay=${ispay}`, function(error, data) {
                    if (error) {
                        console.log(error);
                        response.end("error");
                        return;
                    }
                    console.log("查找去支付订单成功,返回订单页");
                    ejs.renderFile(`static/apply.html`, { applys: data }, function(error, result) {
                        if (error) {
                            console.log(error);
                            return;
                        }
                        console.log("订单页加载成功");
                        response.end(result);
                    })
                })
            })
        } else {
            sql.query(`UPDATE apply SET count=${count} WHERE gname="${gname}" AND username="${username}"`, function(error, data) {
                if (error) {
                    console.log(error);
                    response.end("error")
                    return;
                }
                console.log("支付页面中已有该商品，数量更新成功");
                sql.query(`SELECT * FROM apply WHERE username=${username}`, function(error, data) {
                    if (error) {
                        console.log(error);
                        response.end("error");
                        return;
                    }
                    console.log("查找去支付订单成功,返回订单页");
                    ejs.renderFile(`static/apply.html`, { applys: data }, function(error, result) {
                        if (error) {
                            console.log(error);
                            return;
                        }
                        console.log("订单页加载成功");
                        response.end(result);
                    })
                })
            })
        }



    })


})

//点击确认提交订单
server.get(`/order`, function(request, response) {
    let username = request.query.username;
    let ispay = request.query.ispay;
    let gname = request.query.gname;

    sql.query(`UPDATE apply SET ispay="${ispay}" WHERE username="${username}" AND gname="${gname}"`, function(error, data) {
        if (error) {
            console.log(error);
            response.end("error")
            return;
        }
        response.end("success");
        console.log("支付成功");

    })

})

//查看所有订单
server.get(`/look`, function(request, response) {
    let username = request.query.username;
    let ispay = request.query.ispay;
    sql.query(`SELECT * FROM apply WHERE username="${username}" AND ispay="${ispay}"`, function(error, data) {
        if (error) {
            console.log(error);
            response.end("error")
            return;
        }
        ejs.renderFile(`static/list.html`, { mylist: data }, function(error, result) {
            if (error) {
                console.log(error);
                return;
            }
            console.log("我的订单加载成功");
            response.end(result);
        })
    })
})




// 拦截所有请求，并且声明静态请求目录
server.use(expressStatic(`${__dirname}/static`));

server.listen(port);

console.log(`server is running at ${port}`);